<!--
 * @Description: 会话列表页面
 * @Author: Kerwin
 * @Date: 2024-08-27 10:32:25
 * @LastEditTime: 2024-11-11 16:14:37
 * @LastEditors:  Please set LastEditors
-->
<template>
  <view class="conversation">
    <c_recommendGroup_top />
    <c_conversationList ref="cvsRef" />
  </view>
</template>

<script lang="ts" setup>
import { onBeforeMount } from 'vue';
import { userApi } from '@/api';
import { useUserStore, useChatStore } from '@/store';
import { onReachBottom } from '@dcloudio/uni-app';
import RongIMLib from '../../common/rongCloud/im_init'
import c_recommendGroup_top from './c_recommendGroup_top.vue';
import c_conversationList from './c_conversationList.vue';
import { getImgFullPath } from '@/utils';

const chatStore = useChatStore()
const userStore = useUserStore()
const initRongCloud = () => {
  const { Events } = RongIMLib
  RongIMLib.addEventListener(Events.CONNECTING, () => {
    console.log('正在链接服务器')
  })
  RongIMLib.addEventListener(Events.CONNECTED, () => {
    console.log('已经链接到服务器')
    const includeMuted = false
    const conversationTypes = [
      RongIMLib.ConversationType.PRIVATE,
      RongIMLib.ConversationType.GROUP
    ]
    RongIMLib.getTotalUnreadCount(includeMuted, conversationTypes)
      .then((res) => {
        if (res.code === 0) {
          console.log('未读消息', res.data)
        } else {
          console.log(res.code, res.msg)
        }
      })
      .catch((error) => {
        console.log(error)
      })
    RongIMLib.addEventListener(Events.MESSAGES, (evt) => {
      const { messages } = evt
      console.log('listener==>', evt)
      if (messages && messages.length > 0) {
        messages.forEach((message) => {
          chatStore.setMessage(message, 'add')
        })
      }
    })
    RongIMLib.addEventListener(Events.EXPANSION, (evt) => {
      console.log('扩展信息：', evt)
      const { updatedExpansion, deletedExpansion } = evt;
      console.log('拓展信息更新：', updatedExpansion);
      console.log('拓展信息删除：', deletedExpansion);
    })
    RongIMLib.addEventListener(Events.CONVERSATION, (evt) => {
      console.log('会话监听：', evt);
      chatStore.updateConversation(evt)
    })
  })
}
// 获取用户融云token并建立链接
const getRongCloudToken = async () => {
  uni.showLoading({
    title: '加载中',
    mask: true
  })
  const { code, data } = await userApi.getRongCloudToken(userStore.userInfo?.id).finally(() => {
    uni.hideLoading()
  })
  if (code === 200) {
    const res = await chatStore.connect(data)
    if (res) {
      chatStore.updateMyUserProfile({
        name: userStore.userInfo?.nickname,
        portraitUri: getImgFullPath(userStore.userInfo?.avatar)?.replace(/^https:\/\/|^http:\/\//, "//")
      })
    }
  }
}


onBeforeMount(() => {
  if (userStore.checkLoginState()) {
    initRongCloud()
    getRongCloudToken()
  }
})
onReachBottom(() => {
})
</script>

<style scoped lang="scss">
@import '@/styles/helper.scss';

.conversation {
  display: flex;
  flex-direction: column;
  background: #fff;
  height: 100%
}
</style>